package com.net
{
	import flash.events.Event;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	
	public class SocketServerSecurity
	{
		//--------------------------------
		//单例模式
		private static var _socket_safe:SocketServerSecurity;
		
		public static function getSocketServersecurity():SocketServerSecurity{
			if(_socket_safe==null){
				_socket_safe=new SocketServerSecurity();
			}
			return _socket_safe;
		}
		//-------------------------------------------------------------------
		
		
		
		private var myserver:ServerSocket;//服务器
		
		private var securityXml:XML =<cross-domain-policy><site-control permitted-cross-domain-policies="all"/><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>
		
			
		/**
		 * 开启安全服务器连接
		 */	
		public function SocketServerSecurity()
		{
			myserver=new ServerSocket();
		}
		
		/**
		 * 启动安全服务
		 */
		public function start(_ip:String="127.0.0.1",_port:int=843,security_xml:XML=null):void{
			if(myserver.listening){
				myserver.close();
			}
			if(security_xml!=null){
				securityXml=security_xml;
			}
			myserver.bind(_port,_ip);
			myserver.addEventListener(ServerSocketConnectEvent.CONNECT,onconnect);
			myserver.listen();
		}
		
		/**
		 * 关闭连接
		 */
		public function Close():void{
			myserver.close();
		}
		
		//出现新请求后发送策略文件
		private function onconnect(event:ServerSocketConnectEvent):void{
			var temp_socket:Socket=event.socket;
			temp_socket.writeUTFBytes(securityXml.toString());
			temp_socket.flush();
			temp_socket.close();
		}
	}
}